<template>
  <div class="edit-quote" :key="$route.fullPath">
    <div class="edit-quote-container form-common">
      <h1 class="title-common">{{ isEdit ? '修改名言' : '新增名言' }}</h1>
      
      <div class="form-container">
        <form @submit.prevent="handleSubmit" class="edit-form">
          <!-- 将作家选择移到顶部 -->
          <div class="form-group">
            <label>所属作家</label>
            <select 
              v-if="!writerId"
              v-model="form.writer_name" 
              required
              @change="handleWriterChange"
              class="form-control"
            >
              <option value="">请选择作家</option>
              <option 
                v-for="writer in writers" 
                :key="writer.id" 
                :value="writer.name"
              >
                {{ writer.name }}
              </option>
            </select>
            <div v-if="writerId && selectedWriterName" class="selected-writer">
              <i class="fa fa-user"></i> {{ selectedWriterName }}
            </div>
          </div>

          <!-- 名言内容 -->
          <div class="form-group">
            <label for="content">名言内容</label>
            <textarea 
              id="content" 
              v-model="form.content" 
              required
              placeholder="请输入名言内容"
              rows="6"
              class="form-control"
            ></textarea>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <button type="submit" class="submit-btn">
              {{ isEdit ? '保存修改' : '添加名言' }}
            </button>
            <button type="button" class="cancel-btn" @click="goBack">取消</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 使用通用成功弹窗组件 -->
    <FormModal
      :show="showSuccess"
      title="添加成功"
      message="名言添加成功。"
      :countdown-seconds="countdownSeconds"
      @close="goToSourcePage"
      @confirm="goToSourcePage"
    />
  </div>
</template>

<script>
import FormModal from '@/components/FormModal.vue'

export default {
  name: 'EditQuote',
  components: {
    FormModal
  },
  data() {
    return {
      form: {
        content: '',
        writer_name: '',
        writer_id: ''
      },
      writers: [],
      isEdit: false,
      writerId: null,
      selectedWriterName: '',
      showSuccess: false,
      countdownSeconds: 5,
      countdownTimer: null,
      sourcePage: null
    }
  },
  watch: {
    '$route.query._versionKey': {
      immediate: true,
      handler() {
        console.log('🧩 Detected versionKey change:', this.$route.query._versionKey)
        this.initializeComponent()
      }
    }
  },
  methods: {
    handleWriterChange() {
      const selectedWriter = this.writers.find(w => w.name === this.form.writer_name)
      if (selectedWriter) {
        this.form.writer_id = selectedWriter.id
      } else {
        this.form.writer_id = ''
      }
    },
    async handleSubmit() {
      try {
        const formData = {
          content: this.form.content,
          writer_id: this.form.writer_id
        }

        if (this.isEdit) {
          await this.$axios.put(`/api/quotes/${this.$route.params.id}`, formData)
        } else {
          await this.$axios.post('/api/quotes', formData)
        }

        // 显示成功弹窗
        this.showSuccess = true
        this.countdownSeconds = 5
        this.countdownTimer = setInterval(() => {
          this.countdownSeconds--
          if (this.countdownSeconds <= 0) {
            this.goToSourcePage()
          }
        }, 1000)
      } catch (error) {
        this.$message.error('保存失败：' + (error.response?.data?.message || '未知错误'))
      }
    },
    goBack() {
      this.$router.back()
    },
    goToSourcePage() {
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
      }
      if (this.sourcePage) {
        this.$router.push(decodeURIComponent(this.sourcePage))
      } else {
        this.$router.push('/quotes')
      }
    },
    async fetchWriters() {
      try {
        const response = await this.$axios.get('/api/writers', {
          params: { page: 1, pageSize: 1000 } // 获取所有作家
        })
        this.writers = response.data.writers || []
      } catch (error) {
        console.error('获取作家列表失败：', error)
        this.$message.error('获取作家列表失败')
      }
    },
    async fetchQuote() {
      try {
        const response = await this.$axios.get(`/api/quotes/${this.$route.params.id}`)
        const quote = response.data
        this.form.content = quote.content
        this.form.writer_id = quote.writer_id
        
        // 获取作家名称
        if (quote.writer_id) {
          const writerResponse = await this.$axios.get(`/api/writers/${quote.writer_id}`)
          this.form.writer_name = writerResponse.data.name
        }
      } catch (error) {
        console.error('获取名言详情失败：', error)
        this.$message.error('获取名言详情失败')
      }
    },
    async initializeComponent() {
      console.log('🔄 EditQuote 组件重新初始化:', new Date().toLocaleTimeString())
      console.log('📍 当前路由:', this.$route.fullPath)
      
      // 重置所有数据
      this.form = {
        content: '',
        writer_name: '',
        writer_id: ''
      }
      this.writers = []
      this.isEdit = false
      this.writerId = null
      this.selectedWriterName = ''
      this.showSuccess = false
      this.countdownSeconds = 5
      this.sourcePage = null
      
      // 清除定时器
      if (this.countdownTimer) {
        clearInterval(this.countdownTimer)
        this.countdownTimer = null
      }
      
      // 重新初始化
      this.writerId = this.$route.query.writerId || null
      this.sourcePage = this.$route.query.from || null
      
      if (this.writerId) {
        try {
          const response = await this.$axios.get(`/api/writers/${this.writerId}`)
          this.selectedWriterName = response.data.name
          this.form.writer_id = this.writerId
        } catch (error) {
          console.error('获取作家信息失败：', error)
        }
      } else {
        await this.fetchWriters()
      }
      
      if (this.$route.params.id) {
        this.isEdit = true
        await this.fetchQuote()
      }
    }
  },
  created() {
    this.initializeComponent()
  },
  beforeDestroy() {
    if (this.countdownTimer) {
      clearInterval(this.countdownTimer)
    }
  }
}
</script>

<style scoped>
@import '../assets/css/common.css';

.edit-quote {
  padding: 2rem;
  background-color: #f4f7f6;
  min-height: 100vh;
}

.edit-quote .title-common {
  margin-bottom: 3rem;
}

.edit-quote .title-common h1 {
  text-align: center;
  padding-bottom: 10px;
  border-bottom: #3F6580 solid 1px;
  color: #2c3e50;
  font-size: 24px;
  margin: 0 !important;
  padding-bottom: 10px !important;
}

.edit-quote .form-container {
  margin-top: 3rem;
}

.selected-writer {
  padding: 0.75rem;
  background-color: #e8f5e8;
  border: 1px solid #4caf50;
  border-radius: 4px;
  color: #2e7d32;
  font-weight: 500;
  margin-top: 0.5rem;
}

.selected-writer i {
  margin-right: 0.5rem;
  color: #4caf50;
}
</style> 